package com.axxc.jpa.web;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

@RestController
@RequestMapping("qiniu")
public class QiNiuController {
	@PostMapping("/fileupload")
	public ResponseEntity<String> upload(MultipartFile file) {
		/**
		 * 华东 Zone.zone0() 华北 Zone.zone1() 华南 Zone.zone2() 北美 Zone.zoneNa0()
		 */
		Configuration cfg = new Configuration(Zone.zone0());
		// ...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		// ...生成上传凭证，然后准备上传
		String accessKey = "1vPaogLYQte5Y49MI0XGVoDI20IKbksuJgVtvH8T";
		String secretKey = "6nSZxMPb5hwV1q7vl4Pha2WGRTltkQivmIbFyxtA";
		String bucket = "axxc";
		// 默认不指定key的情况下(为null时)，以文件内容的hash值作为文件名
		String key = file.getOriginalFilename();
		try {
			byte[] uploadBytes = file.getBytes();
			Auth auth = Auth.create(accessKey, secretKey);
			String upToken = auth.uploadToken(bucket);
			Response response = uploadManager.put(uploadBytes, key, upToken);
			// 解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			// System.out.println(putRet.key);
			// System.out.println(putRet.hash);
			// 上传成功返回map
			return new ResponseEntity<String>("http://pcpmpw020.bkt.clouddn.com/" + putRet.key, HttpStatus.OK);
		} catch (MultipartException ex) {
			ex.printStackTrace();
			return new ResponseEntity<String>("上传失败,文件过大", HttpStatus.INTERNAL_SERVER_ERROR);
		} catch (Exception ex) {
			return new ResponseEntity<String>("上传失败,服务异常", HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

}
